/*
 * Copyright 2016 SoChishun.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * URL通用类
 *
 * @author SoChishun
 * @version 1.0 2016-5-26 SoChishun Added.
 */
public class URLUtil {

    final static Logger logger = Logger.getLogger(URLUtil.class.getName());

    /**
     * 功能：检测当前URL是否可连接或是否有效, 描述：最多连接网络 5 次, 如果 5 次都不成功，视为该地址不可用
     *
     * @param urlStr 指定URL网络地址
     * @return URL
     * @see http://wohenshuaiba.iteye.com/blog/1097419
     */
    public static synchronized URL isConnect(String urlStr) {
        if (null == urlStr || urlStr.trim().length() <= 0) {
            return null;
        }
        int state, i = 0;
        URL url = null;
        HttpURLConnection con;
        while (i < 5) {
            try {
                url = new URL(urlStr);
                con = (HttpURLConnection) url.openConnection();
                state = con.getResponseCode();
                logger.log(Level.INFO, "URL connect {0}:{1}", new Object[]{i, state});
                if (200 == state) { // HttpURLConnection.HTTP_OK
                    logger.info("URL connect success!");
                }
                break;
            } catch (Exception ex) {
                i++;
                logger.log(Level.INFO, "URL connect fail: {0}", i);
            }
        }
        return url;
    }

    /**
     * 获取URL内容(带参数)
     * <p>
     * String s = URLEncoder.encode("ra", "GB2312") + "=" + URLEncoder.encode("l", "GB2312") + "&" + URLEncoder.encode("keyword", "GB2312") + "=" + URLEncoder.encode("闽D", "GB2312"); getUrlContent("http://www.baidu.com/jiaojing/ser.php",s);
     * </p>
     *
     * @param urlString
     * @param paramsString
     * @return
     * @since 1.0 2016-5-26 SoChishun Added.
     * @see http://blog.csdn.net/xiaoyu411502/article/details/4500806
     */
    public static String getUrlContent(String urlString, String paramsString) {
        StringBuffer temp = new StringBuffer();
        try {
            HttpURLConnection uc = (HttpURLConnection) new URL(urlString).openConnection();
            uc.setConnectTimeout(10000);
            uc.setDoOutput(true);
            uc.setRequestMethod("GET");
            uc.setUseCaches(false);
            // 要传的参数
            try (DataOutputStream out = new DataOutputStream(uc.getOutputStream())) {
                // 要传的参数
                // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
                out.writeBytes(paramsString);
                out.flush();
            }
            try (InputStream in = new BufferedInputStream(uc.getInputStream())) {
                InputStreamReader rd = new InputStreamReader(in, "Gb2312");
                int c = 0;
                while ((c = rd.read()) != -1) {
                    temp.append((char) c);
                }
            }

        } catch (Exception ex) {
            logger.log(Level.SEVERE, ex.getMessage());
        }
        return temp.toString();
    }

    /**
     * 获取URL内容(无参数)
     *
     * <p>
     * getUrlContent("http://www.pczpg.com/html/bianchengkaifa/Java/20090711/9706.html");
     * </p>
     *
     * @param urlString
     * @return
     * @since 1.0 2016-5-26 SoChishun Added.
     * @see http://www.cnblogs.com/langlang/archive/2010/12/10/1901744.html
     */
    public static String getUrlContent(String urlString) {
        StringBuffer sb = new StringBuffer();
        try {
            java.net.URL url = new java.net.URL(urlString);
            try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
                String line;
                while ((line = in.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, "url [" + urlString + "] can't connect!", ex);
        }
        return sb.toString();
    }

    /**
     * 下载远程文件到本地
     *
     * @param urlString
     * @param filepath
     * @return
     * @since 1.0 2016-5-26 SoChishun Added.
     * @see http://bbs.csdn.net/topics/300120865
     */
    public static boolean saveFile(String urlString, String filepath) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try (InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(filepath)) {
                byte[] b = new byte[1024];
                int len = 0;
                while (len != -1) {
                    fos.write(b, 0, len);
                    len = is.read(b);
                }
                fos.flush();
            }
            return true;
        } catch (Exception ex) {
            logger.log(Level.SEVERE, ex.getMessage());
            return false;
        }
    }

    /**
     * 加载远程文件到本地
     * <p>
     * getURLResource("f:\\测试.xls","http://localhost:8088/bgcl/bussi/ticketQuery.jsp?excel=excel");</p>
     *
     * @param urlStr
     * @param ourputFile
     * @since 1.0 2016-5-26 SoChishun Added.
     * @see http://www.cnblogs.com/jirglt/archive/2012/10/13/2722531.html
     */
    public static void saveFile2(String urlStr, String ourputFile) {
        try (FileWriter fw = new FileWriter(ourputFile); PrintWriter pw = new PrintWriter(fw)) {
            URL resourceUrl = new URL(urlStr);
            InputStream content = (InputStream) resourceUrl.getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = in.readLine()) != null) {
                pw.println(line);
            }
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }

    }
}
